<?php
namespace control;
/*
*委外加工单类
*/

class outsourceProcessClass extends adIndexClass
{
	private const page           = 'outsourceProcess';
	private const table          = 'outsource_process';
	private const tableMx        = 'outsource_process_detail';
	private const table_material = 'outsource_process_material';
	private const title          = '委外加工单';
	private array $stateOption = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'supplier'  => [
                        'name'  => "委外单位",
                        'width' => 200,
                    ],
                    'code'         => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 70,
                    ],
                    'process'          => [
                        'name'  => '工序',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '委外数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'sourceNo'          => [
                        'name'  => '关联源单号',
                        'width' => 150,
                    ],
                    'planTime'          => [
                        'name'  => '计划交货时间',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "物料编码"   => text(array("name" => "materialName")),
                    "物料名称"   => text(array("name" => "code")),
                ],
                [
                    '委外单位' => selectMultiple(["name" => "supplierId", 'table' => "supplier", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' and outsource = '是'", 'sqlField' => 'name']),
                    '工序'  => text(array("name" => "process")),
                    "计划交货时间" => text(array("name" => "startTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'batchDel'})\">删除</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>批量打印</span>\n";
        }
		//返回
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"a.orderNo" => $this->post('orderNo'),
			"b.name"    => $this->post('materialName'),
			"b.code"    => $this->post('code'),
		);
		//全等查询数组
		$equal = array(
			"a.state"      => $this->post('state'),
			"a.supplierId" => $this->post('supplierId'),
			'a.coid'       => self::$coid,
		);
		$and   = '';
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
		}
		if ($this->post('startTime')) {
			$and .= self::timeComparison($this->post('startTime'), 'date', 'planTime');
		}
        if ($this->post('process')) {
            $and .= " and c.processId in (select id from process where name like '%".$this->post('process')."%') ";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.recordDate desc,a.orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array(
		    "table" => self::table . " as a join " . self::table_material . ' as c on c.orderId = a.id join material as b on c.materialId = b.id ',
            'field' => "c.*,b.subject,b.name as materialName,b.code,b.model,a.state,a.supplierId,a.orderNo,a.planTime,a.recordDate,c.sourceId as demandId",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => array("name" => "listId", "value" => $array['orderId']),
				"edit"   => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['orderId'] . "')"),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['orderId'] . "')"),
				'print'  => array('title' => '打印', 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['orderId']}')"),
				'track'  => array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . $url . "&fun=track&orderType=委外加工单&id=" . $array['orderId'] . "')"),
			);
			if ($array['state'] == '已确认' || !$isEdit) {
				unset($dominate['edit']);
			}
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $row[] = supplierClass::getName($array['supplierId']);
                        break;
                    case "process":
                        $process = query('process', "id = '$array[processId]'", "name");
                        $row[] = $process['name'];
                        break;
                    case "num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "sourceNo":
                        $outsourceDemand = query('outsource_demands', "id = '$array[demandId]'");
                        $row[] = $outsourceDemand['sourceNo'];
                        break;
                    case "planTime":
                        $row[] = self::null($array['planTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalArr = find([
            'table'  => self::table . " as a join " . self::table_material . ' as c on c.orderId = a.id join material as b on c.materialId = b.id ',
            'single' => $where,
            'field'  => "ifnull(sum(c.num),0) as num",
        ]);
        $total    = [
            'num'      => self::lostZero($totalArr['num'],'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 单据追踪
	 *
	 * @return string
	 */
	public function track(): string
	{
		$orderTrackClass = new orderTrackClass();
		return $orderTrackClass->home();
	}
    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }
	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id   = $this->get('id') ?: suiji();
		$info = query(self::table, " id = '" . $id . "' ");

		$button[] = [
			'style' => 'li-btn-blue-bg',
			"name"  => "保存",
			"type"  => "点击事件",
			"title" => "保存",
			'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
		];
        $button[] = [
            "name" => "保存并提交",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
		$tr[]     = ['', '源单编号', '产品名称', '物料编码', '物料名称','规格型号', '单位', '工序', '额定数量', '损耗率%', '预计用量', '当前可用库存', '备注'];
		$result   = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['mxNum'=>0,'quantity'=>0];
		foreach ($result['array'] as $k=>$array) {
			$material         = query('material', " id = '$array[materialId]'");
			$unitOption       = machiningOrderClass::unitOption($material['id']);
			$machiningOrderMx = query(self::table_material, "id = '$array[targetSkuId]'");
			$product          = query('material', " id = '$machiningOrderMx[materialId]'");
			$tr[]             = [
                componentClass::tablePperation($k+1,"delTableRow(this);calculateMaterialTotal()").
				hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
				hidden(array('name' => 'targetSkuId[]', 'value' => $array['targetSkuId'])) .
				hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
				$machiningOrderMx['sourceNo'],
				$product['name'],
				$material['code'],
				$material['name'],
				$material['model'],
				select(array('name' => 'unitDetail[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => $unitOption, 'title' => '单位', 'value' => $array['unit'])),
                selectMultiple(array('name' => 'mxProcessId[]', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'value' => $array['processId'])),
				text(array('name' => 'mxNum[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countNum', 'value' => self::lostZero($array['num'], 'numPrecision'))),
				text(array('name' => 'loss[]', 'other' => self::digitalFiltering('rate'), 'blur' => 'countNum', 'value' => $array['loss'] * 100)),
				"<span class='totalNum'>" . self::lostZero($array['quantity'], 'numPrecision') . "</span>",
				"<span class='inventory'>" . machiningOrderClass::inventory($array['materialId'], $array['unit']) . "</span>",
				text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
			];
            $totalArr['mxNum'] += $array['num'];
            $totalArr['quantity'] += $array['quantity'];
		}
        $total = [
            8 => "<span id='total_mxNum'>".self::lostZero($totalArr['mxNum'],'numPrecision')."</span>",
            10 => "<span id='total_quantity'>".self::lostZero($totalArr['quantity'],'numPrecision')."</span>",
        ];
		$list         = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $materialButton        = <<<efo
                <span class="smallButton" onclick="obtainBom()">从BOM获取</span>
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=outsourceProcessEditForm]').serialize())">选择物料</span>
    
efo;
		$table        = <<<efo
                    <div id="material-table-content">{$list}</div>
efo;
        $totalArr = ['num'=>0,'taxMoney'=>0,'moneyWithTax'=>0];
		$materialTr[] = ['', '源单类型', '关联源单', '产品编码', '产品名称', '规格型号', '单位', '工序', '委外数量', '委外单价', '税率%', '税额', '价税合计', 'BOM版本', '备注'];
		if ($this->get('source') == 'outsourceDemand') {
			$listIdArr = explode(',', $this->get('listId'));
			foreach ($listIdArr as $k=>$saleOrderMxId) {
				$outsourceDemand = query('outsource_demands', "id = '$saleOrderMxId'");
				$material        = query('material', " id = '$outsourceDemand[materialId]'");
				$unitOption      = machiningOrderClass::unitOption($material['id']);
				//默认bom
				$detaultBom = query('bom', "materialId = '$material[id]' and state = '启用' and bomType='委外' and isDefault = 1");
				//已进入委外加工单的数量
				$productNum = 0;
				$result     = find(array('table' => self::table_material, 'where' => "sourceId = '$outsourceDemand[id]'"));
				foreach ($result['array'] as $value) {
					$productNum += machiningOrderClass::material_num_change($value['materialId'], $value['unit'], $outsourceDemand['unit'], $value['num']);
				}
				$materialTr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
					hidden(array('name' => 'productId[]', 'value' => self::getId())) .
					hidden(array('name' => 'sourceNo[]', 'value' => $outsourceDemand['sourceNo'])) .
					hidden(array('name' => 'sourceId[]', 'value' => $outsourceDemand['id'])) .
					hidden(array('name' => 'skuId[]', 'value' => $outsourceDemand['materialId'])),
					$outsourceDemand['sourceType'],
					$outsourceDemand['sourceNo'],
					$material['code'],
					$material['name'],
					$material['model'],
					select(array('name' => 'unit[]', 'data' => ['unit' => $outsourceDemand['unit']], 'change' => 'unitChangeProduct', 'option' => $unitOption, 'title' => '单位', 'value' => $material['unit'])),
                    selectMultiple(array('name' => 'processId[]', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'value' => '')),
					text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => $outsourceDemand['num'] - $productNum)),
					text(array('name' => 'price[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('pricePrecision'), 'value' => '')),
					select(array('name' => 'rate[]', 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')))),
					"<span class='taxMoney'></span>",
					"<span class='moneyWithTax'></span>",
					selectMultiple(array('name' => 'bomId[]', 'title' => 'BOM版本', 'table' => 'bom', 'where' => "bomType like '%委外%' and state = '启用' and coid = '" . self::$coid . "' and materialId = '$material[id]' order by time desc", 'sqlId' => 'id', 'sqlField' => 'bomVersion', 'value' => $detaultBom['id'])),
					text(array('name' => 'materialText[]')),
				];
                $totalArr['num'] += $outsourceDemand['num'] - $productNum;
			}
		} else {
			$result = find(array('table' => self::table_material, 'where' => "orderId = '$info[id]' order by list"));
			foreach ($result['array'] as $k=>$array) {
				$relativeNo = $relativeType = '';
				if ($array['sourceTable'] == 'outsource_demands') {
					$outsourceDemand = query('outsource_demands', "id = '$array[sourceId]'");
					$relativeNo      = $outsourceDemand['sourceNo'];
					$relativeType    = $outsourceDemand['sourceType'];
				} elseif ($array['sourceTable'] == 'outsource_contract') {
					$outsource_contract = query('outsource_contract', "id = '$array[sourceId]'");
					$relativeNo         = $outsource_contract['orderNo'];
					$relativeType       = '委外合同';
				}

				$material     = query('material', " id = '$array[materialId]'");
				$unitOption   = machiningOrderClass::unitOption($material['id']);
				$materialTr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
					hidden(array('name' => 'productId[]', 'value' => $array['id'])) .
					hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])) .
					hidden(array('name' => 'sourceNo[]', 'value' => $relativeNo)) .
					hidden(array('name' => 'skuId[]', 'value' => $array['materialId'])),
					$relativeType,
					$relativeNo,
					$material['code'],
					$material['name'],
					$material['model'],
					select(array('name' => 'unit[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChangeProduct', 'option' => $unitOption, 'title' => '单位', 'value' => $array['unit'])),
                    selectMultiple(array('name' => 'processId[]', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'value' => $array['processId'])),
					text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['num'], 'numPrecision'))),
					text(array('name' => 'price[]', 'other' => self::digitalFiltering('pricePrecision'), 'blur' => 'countMoney', 'value' => self::lostZero($array['price'], 'pricePrecision'))),
					select(array('name' => 'rate[]', 'value' => $array['rate'] * 100, 'change' => 'countMoney', 'title' => '税率', 'option' => explode('，', para('taxRate')))),
					"<span class='taxMoney'>" . self::lostZero($array['taxMoney']) . "</span>",
					"<span class='moneyWithTax'>" . self::lostZero($array['money']) . "</span>",
					selectMultiple(array('name' => 'bomId[]', 'title' => 'BOM版本', 'table' => 'bom', 'where' => "bomType like '%委外%' and state = '启用' and coid = '" . self::$coid . "' and materialId = '$array[materialId]' order by time desc", 'sqlId' => 'id', 'sqlField' => 'bomVersion', 'value' => $array['bomId'])),
					text(array('name' => 'materialText[]', 'value' => $array['text'])),
				];
                $totalArr['num'] += $array['num'];
                $totalArr['taxMoney'] += $array['taxMoney'];
                $totalArr['moneyWithTax'] += $array['money'];
			}
		}
        $total = [
            8 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
            11 => "<span id='total_taxMoney'>".self::lostZero($totalArr['taxMoney'])."</span>",
            12 => "<span id='total_moneyWithTax'>".self::lostZero($totalArr['moneyWithTax'])."</span>",
        ];
        $materialTable       = $this->listTable(array('tr' => $materialTr, 'end' => true, 'total' => $total));
        $mxButton = <<<efo
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMaterial',$('form[name=outsourceProcessEditForm]').serialize())">选择物料</span>
efo;
		//表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "委外单位：" => selectMultiple(array('name' => 'supplierId', 'change' => 'getContract', 'value' => $info['supplierId'], 'title' => '请选择', 'table' => 'supplier', 'sqlId' => 'id', 'sqlField' => 'name', 'where' => "outsource = '是' and coid = '" . self::$coid . "'")),
                    must . "单据日期"  => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    "委外合同："     => "<div id='contract' class='full'>" . selectMultiple(["name" => "contractId", "value" => $info['contractId'], 'table' => "outsource_contract", 'where' => "supplierId = '$info[supplierId]' and coid = '" . self::$coid . "' and state = '已通过' order by signedDate asc,time asc", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '请选择']) . "</div>",
                    "计划交货时间：" => text(["name" => "planTime", 'laydate' => [], "value" => $info['planTime']]),
                ],
                [
                    "收货人："   => text(["name" => "contactName", 'class' => 'text', "value" => $info['contactName']]),
                    "收货电话：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                    "收货地址：" => text(["name" => "address", 'class' => 'text', "value" => $info['address']]),
                ],
                [
                    "备注："     => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialMx',
            'title' => '产品明细',
            'button' => $mxButton,
            'html' => $materialTable,
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '所需物料',
            'button' => $materialButton,
            'html' => $table,
        ]);
		$data['html'] = $this->pageEdit([
			"html"  => $body,
			'hidden' => hidden(['name' => 'id', 'value' => $id]) . hidden(array('name' => 'qualityId', 'value' => $this->get('linkId'))),
		]);
		$data['html'] .= <<<efo
<script>
//通过单价计算金额，税额等
function countMoney(e){
    let trObj = $(e).parent().parent();
    countProcess(trObj)
}

function countProcess(trObj){
    let price = trObj.find("[name='price[]']").val();
    let num = trObj.find("[name='num[]']").val();
    let rate = trObj.find("[name='rate[]']").val();
    rate = Number(rate)/100;
    let taxMoney,moneyWithTax;
    //未含税单价
        taxMoney = (Number(price)*Number(num)*rate).toFixed(amountPrecision);
        moneyWithTax = (Number(price)*Number(num)*(1+rate)).toFixed(amountPrecision);
    trObj.find(".moneyWithTax").html(moneyWithTax)
    trObj.find(".taxMoney").html(taxMoney)
    calculateTotal()
}
//计算总金额，总税额
function calculateTotal(){
    let table = $('#materialMx')
    let num = 0,
    taxMoney = 0,
    money = 0;
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var taxMoneyText = table.find(".taxMoney").eq(index).text()
        if(taxMoneyText){
            taxMoney+=Number(taxMoneyText);
        }
        var moneyWithTaxText = table.find(".moneyWithTax").eq(index).text()
        if(moneyWithTaxText){
            money+=Number(moneyWithTaxText);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_taxMoney").text(taxMoney.toFixed(amountPrecision));
    $("#total_moneyWithTax").text(money.toFixed(amountPrecision));
}
//根据委外单位获取委外合同
function getContract(e){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getContract',{supplierId:e.value},function(res) {
          $("#contract").html(res.html);
    },'json');
}
//根据单位转换所需数量和库存
function unitChange(e){
    let unit = e.value;
    if (!unit){
        msg('请选择单位')
        return '';
    }
    let oldUnit = $(e).data('unit');
    $(e).data('unit',unit);
    let loss = $(e).parent().parent().find("[name='loss[]']").val();
    let num = $(e).parent().parent().find("[name='mxNum[]']").val();
    let id = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla=machiningOrder}&fun=unitChange',{unit:unit,oldUnit:oldUnit,num:num,loss:loss,id:id},function(res) {
        if (res.warn===2){
            $(e).parent().parent().find("[name='mxNum[]']").val(res.num);
            $(e).parent().parent().find(".totalNum").html(res.totalNum);
            $(e).parent().parent().find(".inventory").html(res.inventoryNum);
        }else{
            msg(res.warn);
        }
    },'json');
}

//根据BOM计算物料使用量
function obtainBom(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=obtainBom',$('form[name=outsourceProcessEditForm]').serialize(),function(res) {
        if (res.warn ==2){
            $("#material-table-content").empty().append(res.html);
            resetNumber($("#material-table-content"))
        }else{
            msg(res.warn);
        }
    },'json');
}
//计算预定数量
function countNum(e){
    let loss = $(e).parent().parent().find("[name='loss[]']").val();
    let num = $(e).parent().parent().find("[name='mxNum[]']").val();
    $(e).parent().parent().find(".totalNum").html((Number(num)*(1+Number(loss)/100)).toFixed(publicSettings.numPrecision.num))
    calculateMaterialTotal()
}
//计算总金额，总税额
function calculateMaterialTotal(){
    let table = $('#materialTable')
    let num = 0,
    totalNum = 0
    table.find("[name='mxNum[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var totalNumText = table.find(".totalNum").eq(index).text()
        if(totalNumText){
            totalNum+=Number(totalNumText);
        }
    })
    $("#total_mxNum").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_quantity").text(totalNum.toFixed(publicSettings.numPrecision.num));
}
//选择物料
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $('#outsourceProcessAddMx').hide();
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
        calculateMaterialTotal()
    },'json');
}
//选择生产产品
function addMaterial(){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='materialMxForm']").serialize(),function(res) {
         if (res.warn ==2){
             $('#outsourceProcessAddMaterial').hide()
              $("#materialMx tbody").append(res.html);
              resetNumber($("#materialMx"))
              calculateTotal()
         }else{
             msg(res.warn);
         }
        },'json');
}

</script>

efo;
		//返回
		return $this->tab($data);
	}

	/**
	 * 获取合同
	 */
	public function getContract()
	{
		$id           = $this->post('supplierId');
		$json['html'] = selectMultiple([
		    "name" => "contractId",
            'table' => "outsource_contract",
            'where' => "supplierId = '$id' and state = '已通过' and coid = '" . self::$coid . "' order by signedDate asc,time desc",
            'sqlId' => 'id',
            'sqlField' => 'name',
            'title' => '请选择'
        ]);
		return json_encode($json, 320);
	}

	/**
	 * 根据BOM计算物料使用量
	 */
	public function obtainBom(): bool|string
	{
		$productIdArr     = $this->post('productId');
		$materialIdArr = $this->post('skuId');
		$sourceNoArr      = $this->post('sourceNo');
		$bomIdArr         = $this->post('bomId') ?: [];
		$numArr           = $this->post('num');
		$unitArr          = $this->post('unit');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($materialIdArr) || static::is_null_array($productIdArr)) {
			$json['warn'] = '请选择物料';
		} elseif (static::is_null_array($numArr)) {
			$json['warn'] = '您还有物料未填写生产数量';
		} elseif (static::is_null_array($bomIdArr)) {
			$json['warn'] = '您还有物料未选择BOM版本';
		} elseif (static::is_null_array($unitArr)) {
			$json['warn'] = '您还有物料未选择单位';
		} else {
			$tr[] = ['操作', '源单编号', '产品名称', '物料编码', '物料名称', '品牌', '规格型号', '单位', '工序', '额定数量', '损耗率%', '预计用量', '当前可用库存', '备注'];
			foreach ($materialIdArr as $k => $materialId) {
				$bomId         = $bomIdArr[$k];
				$num           = $numArr[$k];
				$unit          = $unitArr[$k];
				$material_list = self::bomMx($bomId, $materialId, $num, $unit);
				$product    = query('material', "id = '$materialId'");
				if (static::is_null_array($material_list)) {
					$this->logText(array('type' => self::page, 'text' => "物料【{$product['code']}-{$product['name']}-{$product['model']}】未在BOM中找到所需物料"));
				} else {
					foreach ($material_list as $array) {
						$material    = query('material', " id = '$array[materialId]'");
						$unitOption  = machiningOrderClass::unitOption($material['id']);
						$num         = self::formattingFigure($array['num'] * (1 + $array['loss']), 'numPrecision');
						$tr[]        = [
                            componentClass::tablePperation('',"delTableRow(this);calculateMaterialTotal()").
							hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
							hidden(array('name' => 'targetSkuId[]', 'value' => $productIdArr[$k])) .
							hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
							$sourceNoArr[$k],
							$product['name'],
							$material['code'],
							$material['name'],
							$material['model'],
							select(array('name' => 'unitDetail[]', 'change' => 'unitChange', 'data' => ['unit' => $material['unit']], 'option' => $unitOption, 'title' => '单位', 'value' => $material['unit'])),
                            selectMultiple(array('name' => 'mxProcessId[]', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'value' => '')),
							text(array('name' => 'mxNum[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countNum', 'value' => self::lostZero($array['num'], 'numPrecision'))),
							text(array('name' => 'loss[]', 'other' => self::digitalFiltering('rate'), 'blur' => 'countNum', 'value' => $array['loss'] * 100)),
							"<span class='totalNum'>{$num}</span>",
							"<span class='inventory'>" . machiningOrderClass::inventory($array['materialId'], $material['unit']) . "</span>",
							text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
						];
					}
				}
			}
			$json['warn'] = 2;
			$json['html'] = $this->tableMany(array('tr' => $tr, 'end' => true));
		}
		return json_encode($json, 320);
	}

	/**
	 * 写入日志
	 *
	 * @param $data
	 * @return string
	 */
	public static function log($data): string
	{
		if (empty($data['text'])) {
			test("【" . $data['type'] . "】日志插入失败，原因：日志说明为空");
			return '';
		} else {
            $data['coid'] = self::$coid;
			if (empty($data['stid'])) {
				$data['stid'] = self::$stid;
			}
			$data['time'] = date("Y-m-d H:i:s");
			return insert(["table" => "log", "field" => $data]);
		}
	}

	/**
	 * 计算BOM用料(主单位)
	 */
	public static function bomMx($bomId, $materialId, $num, $unit, &$material_list = [])
	{
		$bom = query('bom', "id = '$bomId' and state = '启用'");
		if (empty($bom['id'])) {
			self::log(["type" => self::page, "text" => "未找到BOM表"]);
			return $material_list;
		}
		$material    = query('material', "id = '$bom[materialId]'");
		//BOM表头物料单位向物料主单位转化
		if ($bom['unit'] == $material['unit_one']) {
			$bom['num'] = $material['unit_one_num'] * $bom['num'];
		} elseif ($bom['unit'] == $material['unit_two']) {
			$bom['num'] = $material['unit_two_num'] * $bom['num'];
		} elseif ($bom['unit'] != $material['unit']) {
			self::log(["type" => self::page, "text" => "BOM表头物料单位不在物料的单位中"]);
			return $material_list;
		}
		//生产单位向主单位转化
		if ($unit == $material['unit']) {
			$pcs = $bom['num'] > 0 ? ($num / $bom['num']) : 0;//需要几个BOM的子物料
		} elseif ($unit == $material['unit_one']) {
			$num = $num * $material['unit_one_num'];
			$pcs = $bom['num'] > 0 ? ($num / $bom['num']) : 0;//需要几个BOM的子物料
		} elseif ($unit == $material['unit_two']) {
			$num = $num * $material['unit_two_num'];
			$pcs = $bom['num'] > 0 ? ($num / $bom['num']) : 0;//需要几个BOM的子物料
		} else {
			self::log(["type" => self::page, "text" => "物料【{$material['code']}-{$material['name']}-{$material['model']}】生产单位不在物料的单位中"]);
			return $material_list;
		}
		$bomMx = find(array('table' => 'bom_detail', 'where' => "orderId = '$bom[id]' order by list"));
		foreach ($bomMx['array'] as $array) {
			//只找一层
//            if (empty($array['bomId'])){
			//最后一层物料
			$material_list[] = array('materialId' => $array['materialId'], 'loss' => $array['loss'], 'num' => $array['num'] * $pcs);
//            }else{
//                $material_list= self::bomMx($array['bomId'],$array['materialId'],$array['num']*(1+$array['loss'])*$pcs,$array['unit'],$material_list);
//            }
		}
		return $material_list;
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id               = $this->post('id') ?: self::getId();
		$mxIdArr          = $this->post('mxId') ?: [];
		$materialIdArr = $this->post('materialId');
		$numArr           = $this->post('mxNum');
		$unitArr          = $this->post('unitDetail');
		$mxProcessArr     = $this->post('mxProcessId');
		$mxTextArr        = $this->post('mxText');
		$rateArr          = $this->post('rate');
		$priceArr         = $this->post('price');
		$lossArr          = $this->post('loss');
		$targetSkuIdArr   = $this->post('targetSkuId');
		$sourceNoArr      = $this->post('sourceNo');
		$productIdArr     = $this->post('productId') ?: [];
		$sourceIdArr      = $this->post('sourceId');
		$skuIdArr         = $this->post('skuId');
		$numMxArr         = $this->post('num');
		$unitMxArr        = $this->post('unit');
		$processArr       = $this->post('processId');
		$materialTextArr  = $this->post('materialText');
		$bomIdArr         = $this->post('bomId');
		$field            = [
			'text'        => $this->post('text'),
			'contractId'  => $this->post('contractId'),
			'supplierId'  => $this->post('supplierId'),
			'recordDate'  => $this->post('recordDate'),
			'planTime'    => $this->post('planTime'),
			'contactName' => $this->post('contactName'),
			'contactTel'  => $this->post('contactTel'),
			'address'     => $this->post('address'),
		];
		$annotation       = [
			'recordDate' => '单据日期',
			'supplierId' => '委外单位',
		];
		$rules            = [
			'recordDate' => 'required|date',
			'supplierId' => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (static::is_null_array($productIdArr) || static::is_null_array($skuIdArr)) {
			$json['warn'] = '请选择需要生产的产品';
		} elseif (static::is_null_array($numMxArr)) {
			$json['warn'] = '请填写计划数量';
		} elseif (static::is_null_array($unitMxArr)) {
			$json['warn'] = '请选择单位';
		} elseif (static::is_null_array($mxIdArr)) {
			$json['warn'] = '未找到所需物料';
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = '未找到所需物料';
		} elseif (static::is_null_array($numArr)) {
			$json['warn'] = '请填写额定数量';
		} elseif (static::is_null_array($unitArr)) {
			$json['warn'] = '请选择所需物料的单位';
		} elseif (!empty($info['id']) && $info['state'] == '已确认') {
			$json['warn'] = '此委外加工单已确认，不能修改';
		} else {
			$this->startTrans();
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'WWJG' . date('Ymd', strtotime($field['recordDate'])),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => " and coid = '" . self::$coid . "'",
				], $field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $userNo,
					'state'   => '草稿',
					'coid'    => self::$coid,
					'stid'    => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}

			//添加或更新明细
			foreach ($mxIdArr as $k => $nid) {
				$mx          = query(self::tableMx, "id = '$nid'");
				$lossArr[$k] = $lossArr[$k] ?: 0;
				$numArr[$k]  = self::formattingFigure($numArr[$k], 'numPrecision');
				if (!empty($mx['id'])) {
					//更新
					$warn = static::update([
						"table" => self::tableMx,
						"field" => [
							'materialId'    => $materialIdArr[$k],
							'num'           => $numArr[$k],
							'unit'          => $unitArr[$k],
							'processId'     => $mxProcessArr[$k],
							'quantity'      => self::formattingFigure($numArr[$k] * (1 + $lossArr[$k] / 100), 'numPrecision'),
							'loss'          => floatval($lossArr[$k]) / 100,
							'text'          => $mxTextArr[$k],
							'targetSkuId'   => $targetSkuIdArr[$k],
						],
						"where" => " id = '$nid'",
					]);
				} else {
					//新增
					$warn = static::insert([
						"table" => self::tableMx,
						"field" => [
							'id'            => $nid,
							'orderId'       => $id,
							'coid'          => self::$coid,
                            'materialId'    => $materialIdArr[$k],
							'num'           => $numArr[$k],
							'unit'          => $unitArr[$k],
                            'processId'     => $mxProcessArr[$k],
							'quantity'      => self::formattingFigure($numArr[$k] * (1 + $lossArr[$k] / 100), 'numPrecision'),
							'loss'          => floatval($lossArr[$k]) / 100,
							'text'          => $mxTextArr[$k],
							'targetSkuId'   => $targetSkuIdArr[$k],
						],
					]);
				}
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = $warn;
					break;
				}
			}

			//添加或更新生产产品明细
			foreach ($productIdArr as $k => $mxId) {
				$mx          = query(self::table_material, "id = '$mxId'");
				$sourceTable = '';

				if (static::total(array('table' => 'outsource_demands', 'where' => "id = '" . $sourceIdArr[$k] . "'")) > 0) {
					$sourceTable = 'outsource_demands';
				} elseif (static::total(array('table' => 'outsource_contract', 'where' => "id = '" . $sourceIdArr[$k] . "'")) > 0) {
					$sourceTable = 'outsource_contract';
				}
				$rate  = $rateArr[$k] ?: 0;
				$price = $priceArr[$k] ? self::formattingFigure($priceArr[$k], 'pricePrecision') : 0;
				$num   = $numMxArr[$k] ? self::formattingFigure($numMxArr[$k], 'numPrecision') : 0;
				if (!empty($mx['id'])) {
					//更新
					$warn = static::update([
						"table" => self::table_material,
						"field" => [
							'materialId'    => $skuIdArr[$k],
							'sourceId'      => $sourceIdArr[$k],
							'sourceNo'      => $sourceNoArr[$k],
							'sourceTable'   => $sourceTable,
							'num'           => $num,
							'unit'          => $unitMxArr[$k],
                            'processId'     => $processArr[$k],
							'rate'          => $rate / 100,
							'price'         => $price,
							'taxMoney'      => self::formattingFigure($num * $price * ($rate / 100)),
							'money'         => self::formattingFigure($num * $price * (1 + $rate / 100)),
							'bomId'         => $bomIdArr[$k],
							'text'          => $materialTextArr[$k],
						],
						"where" => " id = '$mxId'",
					]);
				} else {
					//新增
					$warn = static::insert([
						"table" => self::table_material,
						"field" => [
							'id'            => $mxId,
							'orderId'       => $id,
							'coid'          => self::$coid,
							'sourceId'      => $sourceIdArr[$k],
							'sourceTable'   => $sourceTable,
							'sourceNo'      => $sourceNoArr[$k],
							'materialId'    => $skuIdArr[$k],
							'num'           => $numMxArr[$k],
							'unit'          => $unitMxArr[$k],
                            'processId'     => $processArr[$k],
							'rate'          => $rate / 100,
							'price'         => $price,
							'taxMoney'      => self::formattingFigure($num * $price * ($rate / 100)),
							'money'         => self::formattingFigure($num * $price * (1 + $rate / 100)),
							'bomId'         => $bomIdArr[$k],
							'text'          => $materialTextArr[$k],
						],
					]);
				}
				if (!in_array($warn, ['新增成功', '更新成功'])) {
					$json['warn'] = $warn;
					break;
				}
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$this->commitTrans();
				delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
				delete(array('table' => self::table_material, 'where' => " id not in ('" . implode("','", $productIdArr) . "') and orderId = '$id'"));
				if ($json['warn'] == '新增成功') {
					auditingFollow(array(
						"type"      => "委外加工单",
						"typeId"    => $info['id'],
						"text"      => "【{$this->control['name']}】新增",
						'job'       => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
						'staffName' => $this->control['name'],
					));
				}
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}


	/**
	 * @return bool|string
	 */
	public function addMx()
	{
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许委外']) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit()
	{
		$mxIdArr = $this->post('mxId');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$tr = [];
			foreach ($mxIdArr as $mxId) {
				$material     = query('material', "id = '$mxId'");
				$unitOption   = machiningOrderClass::unitOption($material['id']);
				$unit         = select(array('name' => 'unitDetail[]', 'change' => 'unitChange', 'data' => ['unit' => $material['unit']], 'option' => $unitOption, 'value' => $material['unit'], 'title' => '单位'));
				$inventoryNum = machiningOrderClass::inventory($material['id'], $material['unit']);
				$tr[]         = [
                    componentClass::tablePperation('',"delTableRow(this);calculateMaterialTotal()").
					hidden(array('name' => 'mxId[]', 'value' => suiji())) .
					hidden(array('name' => 'targetSkuId[]')) .
					hidden(array('name' => 'materialId[]', 'value' => $mxId)),
					'',
					'',
					$material['code'],
					$material['name'],
					$material['model'],
					$unit,
                    selectMultiple(array('name' => 'mxProcessId[]', 'title' => '工序', 'table' => 'process', 'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'value' => '')),
					text(array('name' => 'mxNum[]', 'other' => self::digitalFiltering('numPrecision'), 'blur' => 'countNum')),
					text(array('name' => 'loss[]', 'other' => self::digitalFiltering('rate'), 'blur' => 'countNum')),
					"<span class='totalNum'>0</span>",
					"<span class='inventory'>$inventoryNum</span>",
					text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
				];
			}
			$json['html'] = $this->tableMany(['tr' => $tr, 'thead' => false]);
			$json['warn'] = 2;
		}
		return json_encode($json, 320);
	}


	/**
	 *选择生产产品
	 *
	 * @return bool|string
	 */
	public function addMaterial(): bool|string
	{
		$html =
			materialClass::typeSelect(name: 'type') .
			text(array("name" => "code", "title" => "物料编码")) .
			text(array("name" => "materialName", "title" => "物料名称")) .
			text(array("name" => "model", "title" => "规格型号")) .
			hidden(array('name' => 'contractId', 'value' => $this->post('contractId'))) .
			hidden(array('name' => 'id', 'value' => $this->post('id'))) .
			hidden(array('name' => 'skuId', 'value' => $this->post('skuId') ? implode(',', $this->post('skuId')) : ''));;
		$button = "<input onclick=\"addMaterial()\" type='button' class='searchSub m-l-5' value='提交'>";
		$html   = $this->search($html);
		return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
	}

	/**
	 *添加物料
	 */
	public function addMaterialSearch(): bool|string
	{
		$materialId = $this->post('skuId') ? explode(',', $this->post('skuId')) : [];
		$and           = " and a.supplyControl like '%允许委外%' ";//and a.id not in ('" . implode("','", $materialId) . "')
		if ($this->post('contractId')) {
			$and .= " and a.id in (select materialId from sales_contract_detail where coid = '" . self::$coid . "' and orderId = '" . $this->post('contractId') . "')";
		}
		$like     = [
			'a.name' => $this->post('materialName'),
			'code'   => $this->post('code'),
			'model'  => $this->post('model'),
			'typePath'  => $this->post('type'),
		];
		$equal    = [
			'a.state' => '启用',
			'a.coid'  => self::$coid,
		];
		$where    = search(["like" => $like, "=" => $equal]) . $and;
		$page     = $this->page([
			"table"   => "material as a",
			"field"   => "a.*",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => "a.`time` ASC",
		]);
		$checkAll = $this->checkAll("materialMxForm", "mxId");
		//获取表头
		$tr[] = [$checkAll, '分类', '物料编码', '物料名称', '规格型号'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate = array(
				"box" => array("name" => "mxId", "value" => $array['id']),
			);
			$tr[]     = array(
				$this->dominate($dominate),
                $array['typeName'],
				$array['code'],
				$array['name'],
				$array['model'],
			);
		}
		$json['html'] = $page['hint'] .
            "<form name='materialMxForm'>" .
                hidden(array('name' => 'contractId', 'value' => $this->post('contractId'))) .
                hidden(array('name' => 'id', 'value' => $this->post('id'))) .
                $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 委外合同已在委外加工单中的数量
	 */
	private function contractInNum($id, $contractMxId, $toUnit): float
	{
		$num = 0;
		$all = find(array('table' => self::table_material, 'where' => "orderId !='$id' and sourceId = '$contractMxId' and coid = '" . self::$coid . "'"));
		foreach ($all['array'] as $array) {
			$num += machiningOrderClass::material_num_change($array['materialId'], $array['unit'], $toUnit, $array['num']);
		}
		return self::formattingFigure($num, 'numPrecision');
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMaterialEdit(): bool|string
	{
		$materialIdArr = $this->post('mxId');
		$contractId       = $this->post('contractId');
		$id               = $this->post('id');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (static::is_null_array($materialIdArr)) {
			$json['warn'] = '请选择物料';
		} else {
			$materialTr = [];
			foreach ($materialIdArr as $materialId) {
				$material    = query('material', "id = '$materialId'");
				$unitOption  = machiningOrderClass::unitOption($material['id']);
				$unit        = $material['unit'];
				//默认bom
				$detaultBom   = query('bom', "materialId = '$material[id]' and bomType like '%委外%' and state = '启用' and isDefault = 1");
				$orderNum     = 0;
				$contractMx   = [
					'num'   => 0,
					'price' => 0,
					'rate'  => 0,
				];
				$relativeType = $relativeNo = '';
				if ($contractId) {
					//如果是从合同明细中选择的，则带出合同明细的数据
					$contractMx = query('sales_contract_detail', "materialId = '$materialId' and orderId = '$contractId'");
					$contract   = query('outsource_contract', "id = '$contractId'");
					$unit       = $contractMx['unit'];
					//已进入委外加工单的合同明细数量
					$orderNum     = $this->contractInNum($id, $contractMx['id'], $contractMx['unit']);
					$relativeType = '委外合同';
					$relativeNo   = $contract['orderNo'];
				}
				$num          = ($contractMx['num'] - $orderNum) > 0 ? self::formattingFigure($contractMx['num'] - $orderNum, 'numPrecision') : 0;
				$unitSelect   = select(array(
				    'name' => 'unit[]',
                    'change' => 'unitChangeProduct',
                    'data' => ['unit' => $unit],
                    'option' => $unitOption,
                    'value' => $unit,
                    'title' => '单位'
                ));
				$bom          = selectMultiple(array(
				    'name' => 'bomId[]',
                    'title' => 'BOM版本',
                    'table' => 'bom',
                    'where' => "bomType like '%委外%' and state = '启用' and coid = '" . self::$coid . "' and materialId = '$material[id]' order by time desc",
                    'sqlId' => 'id',
                    'sqlField' => 'bomVersion',
                    'value' => $detaultBom['id']
                ));
				$priceText    = text(array('name' => 'price[]', 'value' => $contractMx['price'], 'blur' => 'countMoney', 'type' => 'number'));
				$rateText     = select(array(
				    'name' => 'rate[]',
                    'value' => $contractMx['rate'] * 100,
                    'change' => 'countMoney',
                    'title' => '税率',
                    'option' => explode('，', para('taxRate'))
                ));
				$result       = saleOrderClass::isTax($num, $contractMx['price'], $contractMx['rate']);
				$materialTr[] = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
					hidden(array('name' => 'productId[]', 'value' => suiji())) .
					hidden(array('name' => 'sourceId[]', 'value' => $contractId)) .
					hidden(array('name' => 'sourceNo[]', 'value' => $relativeNo)) .
					hidden(array('name' => 'skuId[]', 'value' => $material['id'])),
					$relativeType,
					$relativeNo,
					$material['code'],
					$material['name'],
					$material['model'],
					$unitSelect,
                    selectMultiple(array(
                        'name' => 'processId[]',
                        'title' => '工序',
                        'table' => 'process',
                        'where' => "state = '启用' and coid = '" . self::$coid . "' order by orderNo asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'value' => ''
                    )),
					text(array(
					    'name' => 'num[]',
                        'other' => self::digitalFiltering('numPrecision'),
                        'blur' => 'countMoney',
                        'value' => self::lostZero($num, 'numPrecision')
                    )),
					$priceText,
					$rateText,
					"<span class='taxMoney'>" . self::lostZero($result['taxMoney']) . "</span>",
					"<span class='moneyWithTax'>" . self::lostZero($result['money']) . "</span>",
					$bom,
					text(array('name' => 'materialText[]')),
				];
			}
			$json['warn'] = 2;
			$json['html'] = $this->tableMany(['tr' => $materialTr, 'thead' => false]);
		}
		return json_encode($json, 320);
	}


	/**
	 * 启用/停用
	 */
	public function stateSwitch(): bool|string
	{
		$isClose = $this->post('type');
		//生成表单
		$html = $this->layerEdit(array(
			"table"     => array(
				array(
					"提示：" => "是否确认" . ($isClose == 1 ? '关闭' : '开启') . "此订单？",
				),
			), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose)),
		));
		//返回
		return $this->layer(array("title" => "订单状态", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
	}

	/**
	 * 启用/停用
	 */
	public function stateSwitchEdit(): bool|string
	{
		$idArr   = $this->post('id') ? [$this->post('id')] : $this->post('listId');
		$isClose = $this->post('type');
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有" . self::title . "的编辑权限";
		} elseif (empty($idArr) || !is_array($idArr)) {
			$json['warn'] = "请选择数据";
		} else {
			$field        = [
				'isClose' => $isClose,
			];
			$json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				$type = $isClose == 1 ? '关闭' : '开启';
				foreach ($idArr as $id) {
					auditClass::operateRecord($id, '委外加工单', $type);
				}
				//添加日志
				$text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $type . '成功';
				$json['warn']     = 2;
			}
		}
		//返回
		return json_encode($json, 320);
	}


	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data = array(
				"id"   => $info['id'],
				'menu' => [
					'detail' => '基本信息',
				],
			);

			$button = [];
			if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
				$button[] = [
					"name"  => "确认",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'confirm', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($info['state'] == '草稿') {
				//按钮
				$button[] = [
					"name"  => "提交",
					"type"  => "弹出层",
					"cla"   => $this->get('cla'),
					"fun"   => "operate",
					"post"  => ["act" => 'commit', "id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			if ($info['state'] != '已确认') {
				if ($this->power(self::page, "edit")) {
					//按钮
					$button[] = [
						"name"  => "编辑",
						"type"  => "顶部页卡",
						"title" => "编辑用户",
						"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

					];
				}
				if ($this->power(self::page, "del")) {
					//按钮
					$button[] = [
						"name" => "删除",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'del', "id" => $info['id']],
					];
				}
			}
			//按钮
			$button[] = [
				"name" => "打印",
				"type" => "点击事件",
				"fun"  => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
			];


			if ($this->power(self::page, "confirm") && $info['state'] == '已确认' && !$info['isClose']) {
				$button[] = [
					"name" => "撤回",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'cancel', "id" => $info['id']],
				];
			}
			if ($this->power(self::page, "edit") && $info['state'] == '已确认') {
				//按钮
				$isClose  = $info['isClose'] == 1 ? 0 : 1;
				$name     = $info['isClose'] == 1 ? '开启' : '关闭';
				$button[] = [
					"name" => $name,
					"type" => "点击事件",
					"fun"  => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
				];
			}
			$button[] = [
				"name"  => "单据追踪",
				"type"  => "顶部页卡",
				"title" => "单据追踪",
				"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=track&orderType=委外加工单&id=" . $info['id'],
			];
			//操作记录
            $button[] = self::operateLogBut($info['id']);

			$tr[]   = ['源单编号', '产品名称', '物料编码', '物料名称', '规格型号', '单位', '工序', '额定数量', '损耗率%', '预计用量', '当前可用库存', '备注'];
			$result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
			$totalArr = ['total_num'=>0,'quantity'=>0];
			foreach ($result['array'] as $array) {
				$material           = query('material', " id = '$array[materialId]'");
				$inventoryNum       = machiningOrderClass::inventory($array['materialId'], $array['unit']);
				$outsourceMaterial  = query(self::table_material, " id = '$array[targetSkuId]'");
				$product            = query('material', " id = '$outsourceMaterial[materialId]'");
				$process = query('process', " id = '$array[processId]'");
				$tr[]               = [
                    $outsourceMaterial['sourceNo'],
					$product['name'] ,
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
                    $process['name'],
					self::lostZero($array['num'], 'numPrecision'),
					($array['loss'] * 100) . '%',
					self::lostZero($array['quantity'], 'numPrecision'),
					$inventoryNum,
					$array['text'],
				];
                $totalArr['total_num'] += $array['num'];
                $totalArr['quantity'] += $array['quantity'];
			}
            $total_tr = [
                7 => self::lostZero($totalArr['total_num'], 'numPrecision'),
                9 => self::lostZero($totalArr['quantity'], 'numPrecision'),
            ];

			$materialTr[] = ['源单类型', '源单号', '产品编码', '产品名称', '规格型号', '单位', '工序', '委外数量', '委外单价', '税率', '税额', '价税合计', 'BOM版本', '备注'];
			$result       = find(array('table' => self::table_material, 'where' => "orderId = '$info[id]' order by list"));
			$totalMaterialArr = ['num'=>0,'taxMoney'=>0,'money'=>0];
			foreach ($result['array'] as $array) {
				$material    = query('material', " id = '$array[materialId]'");
				$relativeNo  = $relativeType = '-';
				if ($array['sourceTable'] == 'outsource_demands') {
					$outsourceDemand = query('outsource_demands', "id = '$array[sourceId]'");
					$relativeNo      = $outsourceDemand['sourceNo'];
					$relativeType    = $outsourceDemand['sourceType'];
				}
				$bom          = query('bom', "id = '$array[bomId]'");
                $process = query('process', " id = '$array[processId]'");
				$materialTr[] = [
					$relativeType,
					$relativeNo,
					$material['code'],
					$material['name'],
					$material['model'],
					$array['unit'],
                    $process['name'],
					self::lostZero($array['num'], 'numPrecision'),
					self::lostZero($array['price'], 'pricePrecision'),
					$array['rate'] * 100,
					self::lostZero($array['taxMoney']),
					self::lostZero($array['money']),
					$bom['bomVersion'],
					$array['text'],
				];
                $totalMaterialArr['num'] += $array['num'];
                $totalMaterialArr['taxMoney'] += $array['taxMoney'];
                $totalMaterialArr['money'] += $array['money'];
			}
            $total_material_tr = [
                7 => self::lostZero($totalMaterialArr['num'], 'numPrecision'),
                10 => self::lostZero($totalMaterialArr['taxMoney']),
                11 => self::lostZero($totalMaterialArr['money']),
            ];
			$supplier = query('supplier', "id = '$info[supplierId]'");
			$contract = query('outsource_contract', "id = '$info[contractId]'");
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow(array(
				'详细信息' => array(
					array(
						"委外单位" => $supplier['name'],
						"单据日期" => $info['recordDate'],
						"委外合同" => $contract['orderNo'],
                        "计划交货时间" => $info['planTime'],
					),
					array(
                        "收货人"       => $info['contactName'],
						"收货电话"     => $info['contactTel'],
                        "收货地址" => $info['address'],
                        "单据编号" => $info['orderNo'],
					),
                    array(
                        "制单人"   => self::findStaff($info['stid']),
                        "状态"     => $info['state']
                    ),
					array(
						"备注"     => pre($info['text']),
					),

				),
			));
            $data['html'] .= $this->detailList([
                'title' => '产品明细',
                'html' => $this->listTable(array('tr' => $materialTr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_material_tr)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '所需物料',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr)),
            ]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}


	/**
	 * 确认
	 */
	public function confirmEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '已确认',
			'checkId'     => self::$stid,
			'confirmTime' => $this->time,
		];
		if (!$this->power(self::page, 'confirm')) {
			$json['warn'] = '你还没有确认权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此委外加工单';
		} elseif ($info['state'] != '待确认') {
			$json['warn'] = '此加工单不是待确认状态，不能确认';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '委外加工单', '确认');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 撤回
	 */
	public function cancelEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state'       => '草稿',
			'checkId'     => '',
			'confirmTime' => '',
		];
		if (!$this->power(self::page, 'cancel')) {
			$json['warn'] = '你还没有撤回权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此委外加工单';
		} elseif ($info['state'] != '已确认') {
			$json['warn'] = '此委外加工单不是已确认状态，无需撤回';
		} elseif (static::total(array('table' => 'outsource_pick_order_detail', "where" => "sourceId in (select id from " . self::tableMx . " where orderId = '$info[id]')  and coid = '" . self::$coid . "'")) > 0) {
			$json['warn'] = '已有委外发料单或委外退料单关联此加工单，不能撤回';
		} elseif (static::total(array('table' => 'outsource_in_order_detail', "where" => "sourceId in (select id from " . self::table_material . " where orderId = '$info[id]')  and coid = '" . self::$coid . "'")) > 0) {
			$json['warn'] = '已有委外收货单关联此加工单，不能撤回';//生产入库单
		} elseif (static::total(array('table' => 'machining_send_order', "where" => "machiningOrderId= '$info[id]' and coid = '" . self::$coid . "'")) > 0) {
			$json['warn'] = '已有委外派工单关联此加工单，不能撤回';//工序报工单
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '委外加工单', '撤回');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 提交
	 */
	public function commitEdit()
	{
		$id    = $this->post('id');
		$info  = query(self::table, " id = '$id'");
		$field = [
			'state' => '待确认',
		];
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($info['id'])) {
			$json['warn'] = '未找到此委外加工单';
		} elseif ($info['state'] != '草稿') {
			$json['warn'] = '此单据不是草稿状态，不能提交';
		} else {
			$json['warn'] = update(array(
				"table" => self::table,
				"field" => $field,
				"where" => "id = '$info[id]'",
			));
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				auditClass::operateRecord($info['id'], '委外加工单', '提交');
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
			}
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 列表删除
	 */
	public function batchDel(): bool|string
	{
		$listId = $this->post('listId');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除" . self::title . "的权限";
		} elseif (empty($listId) || !is_array($listId)) {
			$json['warn'] = '您还没有选择单据';
		} else {
			$x    = 0;
			$text = '';
			$all  = find(array('table' => self::table, "where" => "coid = '" . self::$coid . "' and id in ('" . implode("','", $listId) . "')"));
			foreach ($all['array'] as $array) {
				if ($array['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$array[id]' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$array[id]' "));
					delete(array("table" => self::table_material, "where" => " orderId = '$array[id]' "));
					delete(array("table" => "auditing_follow", "where" => " typeId = '$array[id]' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $array['id'] . "】,单号【{$array['orderNo']}】" . $warn . "。<br>";
			}
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$json['warn'] = 2;
			$json['msg']  = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
		}
		return json_encode($json, 320);
	}

	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = $word = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			case 'batchDel':
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'batchDel';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
			case 'confirm':
				$act      = 'confirm';
				$msg      = '确认';
				$title    = '是否已确认此委外加工单，确认后将不可修改？';
				$function = 'confirmEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'commit':
				$act      = 'edit';
				$msg      = '编辑';
				$title    = '是否确认提交此委外加工单？';
				$function = 'commitEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'cancel':
				$act      = 'cancel';
				$msg      = '撤回';
				$title    = '是否确认撤回此委外加工单？';
				$function = 'cancelEdit';
				$form     = self::page . 'OperateForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
					delete(array("table" => self::table_material, "where" => " orderId = '$id' "));
					delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 批量打印
	 *
	 * @return string
	 */
	public function batchPrint(): string
	{
		$lists = $this->get('lists');
		if (empty($lists)) {
			exit('参数错误');
		} else {
			$listId = base64_decode($lists, true);
			$array  = explode(',', $listId);
			$data   = [];
			foreach ($array as $id) {
				$data[] = static::printPage($id, false);
			}
			return (new printTemplateClass())->start(self::page, $data);
		}
	}

	/**
	 * 打印
	 *
	 * @return string
	 */
	public function printPage($param = '', $isReturn = true): string|array
	{
		$id                   = $param ?: $this->get('id');
		$info                 = query(self::table, " id = '$id'");
		$info['companyName']  = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
		$info['title']        = self::title;
		$info['lineName']     = query('supplier', "id = '" . $info['supplierId'] . "'")['name']; //公司名称
		$info['materialName'] = '产品明细';
		$info['printTime']    = $this->time;
		$info['stid']         = self::findStaff($info['stid']);
		$info['qr']           = "source=" . self::table . "&id=" . $info['id'];
		$info['tags']         = orderTagClass::getTagName($info['id']);
		$detail               = find(['table' => self::table_material, 'where' => "orderId = '$info[id]' order by list asc"])['array'];
		$items                = [];
		$x                    = 1;
		$totalNum             = 0;
		foreach ($detail as $array) {
			$material    = query('material', "id = '$array[materialId]'");
			$relativeNo  = $relativeType = '-';
			if ($array['sourceTable'] == 'outsource_demands') {
				$outsourceDemand = query('outsource_demands', "id = '$array[sourceId]'");
				$relativeNo      = $outsourceDemand['sourceNo'];
			}
			$items[] = [
				'no'              => $x,
				'relativeNo'      => $relativeNo,
				'materialCode'    => $material['code'],
				'materialName'    => $material['name'],
				'model'           => $material['model'],
				'unit'            => $array['unit'],
				'text'            => $array['text'],
				'num'             => self::lostZero($array['num'], 'numPrecision'),
			];
			$x++;
			$totalNum += $array['num'];
		}
		$append         = [
			'no'  => '合计',
			'num' => self::lostZero($totalNum, 'numPrecision'),
		];
		$items[]        = $append;
		$info['detail'] = $items;
		if ($isReturn) {
			return (new printTemplateClass())->start(self::page, $info);
		} else {
			return $info;
		}
	}

}
